import storage from '../../../utils/storage'
import userApi from '../../../api/userInfo'
import loginApi from '../../../api/login'
import { hasLogin, toast, hideLoading } from '../../../utils/util'
Page({
  data: {
    statusBarHeight: getApp().globalData.statusBarHeight,
    image: '/static/icons/icon01.png',
    list: [
      {
        name: '新增设备',
        icon: '/static/icons/icon01.png',
        bgColor: '#ebfff9',
        url: '/pages/mine/newAdd/index'
      },
      {
        name: '分组管理',
        icon: '/static/icons/icon05.png',
        bgColor: '#ebf2ff',
        url: '/pages/mine/group/index'
      },
      {
        name: '常见问题',
        icon: '/static/icons/icon02.png',
        bgColor: '#f2faff',
        url: '/pages/mine/problem/index'
      },
      {
        name: '异常记录',
        icon: '/static/icons/icon04.png',
        bgColor: '#faf6ed',
        url: '/pages/mine/abnormal/index'
      },
      {
        name: '退出登录',
        icon: '/static/icons/icon03.png',
        bgColor: '#fcf5f5',
        url: null
      }
    ],
    userInfo: null,
  },
  onLoad: function (options) {
    if(!hasLogin()) {
      this.login();
    }
  },
  onShow() {
    this.getUserInfo();
  },
  jump (e) {
    let { url } = e.currentTarget.dataset;
    console.log(url)
    if (hasLogin()) {
      if(url === null) {
        loginApi.logout().then(res => {
          toast(res.msg);
          storage.clear();
          setTimeout(()=>{
            this.setData({
              userInfo: null
            })
            wx.navigateTo({
              url: '/pages/login/login',
            })
          },1500)
        })
      } else {
        wx.navigateTo({
          url: url,
        })
      }
    } else {
      wx.navigateTo({
        url: '/pages/login/login',
      })
    }
    
  },
  // 用户信息
  getUserInfo () {
    userApi.getUserInfo().then(res => {
      storage.set('userInfo', res.data);
      this.setData({
        userInfo: res.data
      })
    })
  },
  login() {
    wx.login({
      success: res => {
        if (res.code) {
          let params = {
            loginCode: res.code,
            state: getApp().globalData.clientId
          }
          loginApi.login(params).then(res => {
            if (res.data.bindingFlag) {
              storage.set('token',res.data.access_token);
            }
          })
        }
      }
    })
  },
});